import type { MockMethod } from 'vite-plugin-mock'
import fs from 'fs'
import path from 'path'

//https://github.com/vbenjs/vite-plugin-mock/tree/main#mock-file-example
/*MockMethod
{
  // request url
  url: string;
  // request method
  method?: MethodType;
  // Request time in milliseconds
  timeout?: number;
  // default: 200
  statusCode?:number;
  // response data (JSON)
  response?: ((opt: { [key: string]: string; body: Record<string,any>; query:  Record<string,any>, headers: Record<string, any>; }) => any) | any;
  // response (non-JSON)
  rawResponse?: (req: IncomingMessage, res: ServerResponse) => void;
}
*/
export default [
  {
    url: '/api/get',
    method: 'get',
    response: () => {
      return {
        code: 0,
        data: {
          content: 'this is mock data from /api/get'
        }
      }
    }
  },
  {
    url: '/api/post',
    method: 'post',
    timeout: 2000,
    response: ()=>{
      return {
        code: 0,
        data: {
          content: 'this is mock data from /api/post'
        }
      }
    }
  },
  {
    url: '/api/image',
    method: 'get',
    rawResponse: async (_req: any, res: any) => {
      const imagePath = path.join(__dirname, 'demo.gif')

      fs.readFile(imagePath, (err, data) => {
        if (err) {
          res.statusCode = 500
          res.setHeader('Content-Type', 'text/plain')
          res.end('Error: Unable to read image file.')
        } else {
          // 设置内容类型为 image/jpeg（或其他适当的类型）
          res.setHeader('Content-Type', 'image/gif')
          res.statusCode = 200
          res.end(data) // 将图片文件的二进制数据发送给客户端
        }
      })
    }
  }
] as MockMethod[]

//todo
//https://github.com/vbenjs/vite-plugin-mock/issues/98
//vite 运行时,修改mock文件会生成很多个xxx.mjs文件
//暂时解决方案：降级为2.9.8

//https://github.com/vbenjs/vite-plugin-mock/issues/45
//请问 url 是否支持 正则？